package com.longg.service.impl;

import com.longg.dao.DeptDao;
import com.longg.dao.UserDao;
import com.longg.model.Dept;
import com.longg.model.User;
import com.longg.service.IDeptService;

import java.util.*;

public class DeptServiceImpl implements IDeptService {
    private DeptDao deptDao = new DeptDao();
    private UserDao userDao = new UserDao();


    @Override
    public List<Dept> findAll() {
        return deptDao.findAll();
    }

    @Override
    public List<Map<String, Object>> findDeptAndUser() {
        List<Map<String, Object>> deptAndUser = deptDao.findDeptAndUser();
        List<Map<String, Object>> returnList = new ArrayList<>();
        Map<String,Object> deptMap;
        Set<Integer> deptIds = new HashSet<>();
        List<Map<String,Object>> userList;
        Map<String,Object> usermap;
        for(Map<String,Object> map : deptAndUser){
            int deptId = (int) map.get("id");
            if(!deptIds.contains(deptId)){
                deptIds.add(deptId);
                deptMap = new HashMap<>();
                deptMap.put("dept_id",deptId);
                deptMap.put("dept_name",map.get("name"));
                deptMap.put("userNum",1);
                userList = new ArrayList<>();
                usermap = new HashMap<>();
                usermap.put("user_id",map.get("user_id"));
                usermap.put("real_name",map.get("real_name"));
                userList.add(usermap);
                deptMap.put("userList",userList);
                returnList.add(deptMap);
            }else{
                for(Map<String, Object> map2 : returnList){
                    if (map2.get("dept_id").equals(deptId)){
                        int count = (int) map2.get("userNum");
                        map2.put("userNum",count + 1);
                        usermap = new HashMap<>();
                        userList = (List<Map<String, Object>>) map2.get("userList");
                        usermap.put("user_id",map.get("user_id"));
                        usermap.put("real_name",map.get("real_name"));
                        userList.add(usermap);
                        break;
                    }
                }
            }
        }
        return returnList;
    }

}
